import React from 'react';
import { connect } from 'dva/index';
import { Button, Col, DatePicker, Form, Input, message, Popconfirm, Radio, Row, Table } from 'antd';
import Constants from '../../../utils/Constants'
import RightConstants from '../../../utils/RightConstants';
import RightBox from '../../../components/commons/RightBox';
import InvoiceDetail from '../../../components/drawback/invoiceDetail';
import TaxStatus from '../../../components/drawback/taxStatus';

const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const R = require('ramda');
const statusArr = ['删除', '草稿', '待处理', '作废审批中', '确认作废', '仲裁作废', '已处理'];
const openInvoiceStatus = ['未做开票资料', '待做开票资料', '待收票', '待审核', '待验票', '已验票'];
const transferaccountstatus = ['待退税', '退税到账', '暂缓退税', '税局发函'];
const FormItem = Form.Item;
const invoice = Form.create()(class Invoice extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'tax/query',
            payload: { ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE) }
        });
    }

    handleOpen = (id, disabled, operate) => {
        this.props.dispatch({ type: 'tax/get', payload: { id } })
        this.invoiceDetail.handleOpen(disabled, operate);
    }

    handleOpenUpateOrder = (id) => {
        this.props.dispatch({ type: 'tax/get', payload: { id } })
        this.taxStatus.handleOpen();
    }

    handleSearch = () => {
        let values = this.props.form.getFieldsValue();
        let newPage = this.props.tax.page;
        newPage.page = 1;
        this.props.dispatch({
            type: 'tax/query',
            payload: {
                ...values,
                ...R.pick(['page', 'size'], newPage)
            }
        });
    }

    columns = [
        { title: '订单号', dataIndex: 'orderno', key: 'orderno' },
        { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },
        { title: '报关单号', dataIndex: 'cstdeclarationno', key: 'cstdeclarationno' },
        { title: '下单时间', dataIndex: 'createtime', key: 'createtime' },
        { title: '出口日期', dataIndex: 'exporttime', key: 'exporttime' },
        { title: '放行状态', dataIndex: 'passStatus', key: 'passStatus' },
        { title: '放行日期', dataIndex: 'passtime', key: 'passtime' },
        { title: '已放行天数', dataIndex: 'passDate', key: 'passDate' },
        {
            title: '发票状态', dataIndex: 'openinvoicestatus', key: 'openinvoicestatus', render: (text, record, index) => {
                return openInvoiceStatus[record.openinvoicestatus];
            }
        },
        {
            title: '发票状态', dataIndex: 'presentstatus', key: 'presentstatus', render: (text, record, index) => {
                return text === '1' ? '已交单' : '未交单';
            }
        },
        {
            title: '发票状态', dataIndex: 'transferaccountstatus', key: 'transferaccountstatus', render: (text, record, index) => {
                return transferaccountstatus[record.transferaccountstatus];
            }
        },
        { title: '外商名称', dataIndex: 'buyerName', key: 'buyerName' },
        { title: '跟单员', dataIndex: 'creatorName', key: 'creatorName' },
        {
            title: '操作', key: 'oprator',
            render: (text, record, index) => {
                let invoiceGenerate = <RightBox resource={RightConstants.DRAW.DRAW_INVOICE_GENERATE} split={true}>
                    <a href="#" onClick={this.handleOpen.bind(this, record.id, false, record.openinvoicestatus)}>{record.openinvoicestatus == 1 ? '做开票资料' : '重做开票资料'}</a></RightBox>
                let recInvoice = <RightBox resource={RightConstants.DRAW.DRAW_INVOICE_REC} split={true}>
                    <a href="#" onClick={this.handleOpen.bind(this, record.id, false, "3")}>收票</a></RightBox>
                let checkin = <RightBox resource={RightConstants.DRAW.DRAW_INVOICE_CHECKIN} split={true}>
                    <a href="#" onClick={this.handleOpen.bind(this, record.id, false, record.openinvoicestatus)}>认证发票</a></RightBox>
                let cancelCheck = <RightBox resource={RightConstants.DRAW.DRAW_INVOICE_CHECKED_CANCEL} split={true}><span>
                    <Popconfirm placement="leftTop" title={'取消验票订单将回退至待验票状态，是否继续？'}
                        onConfirm={() => {
                            this.props.dispatch({
                                type: 'tax/updateOrder',
                                payload: {
                                    id: record.id,
                                    openinvoicestatus: 4,
                                    onSuccess: () => {
                                        this.handleSearch();
                                    }
                                }
                            })
                        }} okText="是" cancelText="否">
                        <a href="#" disabled={this.props.disabled}>取消验票</a>
                    </Popconfirm></span></RightBox>

                recInvoice = record.openinvoicestatus == 2 ? recInvoice : "";
                invoiceGenerate = record.openinvoicestatus < 3 ? invoiceGenerate : "";
                checkin = record.openinvoicestatus == 4 ? checkin : "";
                cancelCheck = record.openinvoicestatus == 5 ? cancelCheck : "";
                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, record.openinvoicestatus)}>查看</a>
                let updateOrder = <RightBox resource={RightConstants.DRAW.DRAW_TAX_EDIT} split={true}>
                    <a href="#" onClick={this.handleOpenUpateOrder.bind(this, record.id)}>更新退税状态</a></RightBox>
                updateOrder = record.openinvoicestatus == 5 ? updateOrder : "";
                return <span>{invoiceGenerate}{recInvoice}{checkin}{updateOrder}{cancelCheck}{viewLink}</span>;
            }
        }
    ];

    render() {
        let dataSource = R.isNil(this.props.tax.dataSource) ? {} : this.props.tax.dataSource;
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            current: this.props.tax.page.page,
            pageSize: this.props.tax.page.size,
            total: this.props.tax.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = R.pick(['page', 'size'], this.props.tax.page);
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'tax/query',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = R.pick(['page', 'size'], this.props.tax.page);
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'tax/query',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            }
        }
        return (
            <div>
                <Row>
                    <Col span={6}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(<Input />)}</FormItem></Col>
                    <Col span={7} style={{ float: 'right' }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('invoiceStatus', {
                                initialValue: ""
                            })(
                                <RadioGroup style={{ width: 800 }} >
                                    <Radio value="">全部</Radio>
                                    <Radio value="1">待做开票资料</Radio>
                                    <Radio value="2">待收票</Radio>
                                    <Radio value="4">待验票</Radio>
                                    <Radio value="5">已收票</Radio>
                                </RadioGroup>
                                )}
                        </FormItem>
                    </Col>
                </Row>

                <Table loading={this.props.loading} rowKey={record => record.id} dataSource={this.props.tax.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />
                <InvoiceDetail wrappedComponentRef={(inst) => this.invoiceDetail = inst} refreshList={this.handleSearch} />
                <TaxStatus wrappedComponentRef={(inst) => this.taxStatus = inst} refreshList={this.handleSearch} />
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.tax, tax: state.tax
    };
}

export default connect(mapStateToProps)(invoice);